import { Toast } from 'antd-mobile';
import { history } from 'umi';
import * as keys from 'numeric-keyboard/lib/keys';

const keyboardLayout = [
  [
    {
      key: keys.ONE,
    },
    {
      key: keys.TWO,
    },
    {
      key: keys.THREE,
    },
    {
      key: keys.DEL,
    },
  ],
  [
    {
      key: keys.FOUR,
    },
    {
      key: keys.FIVE,
    },
    {
      key: keys.SIX,
    },
    {
      key: keys.ENTER,
      rowspan: 3,
    },
  ],
  [
    {
      key: keys.SEVEN,
    },
    {
      key: keys.EIGHT,
    },
    {
      key: keys.NINE,
    },
  ],
  [
    {
      key: keys.ZERO,
      colspan: 2,
    },
    {
      key: keys.DOT,
    },
  ],
];

// 包装sessionStorage，提供storage使用
const storage = (function (type) {
  if (!type) {
    throw new Error('storage must have a type');
  }

  const setItem = function (key, value) {
    sessionStorage.setItem(type + '-' + key, JSON.stringify(value));
  };

  const getItem = function (key) {
    const val = sessionStorage.getItem(type + '-' + key);
    return JSON.parse(val);
  };

  const clear = function () {
    sessionStorage.clear();
  };

  const removeItem = function (key) {
    sessionStorage.removeItem(type + '-' + key);
  };

  return {
    setItem: setItem,
    getItem: getItem,
    clear: clear,
    removeItem: removeItem,
  };
})('mp');

const browser = (function () {
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf('Alipay') !== -1) return 'ALIPAY';
  if (userAgent.indexOf('MicroMessenger') !== -1) return 'WECHAT';
  if (userAgent.indexOf('UnionPay') !== -1) return 'UNIONPAY';
  return -1;
})();

const callpay = ({
  appId,
  timeStamp,
  nonceStr,
  signType,
  paySign,
  packageData,
  cashPayAmt = '',
}) => {
  const onBridgeReady = () => {
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      {
        appId, //公众号名称，由商户传入
        timeStamp, //时间戳，自1970年以来的秒数
        nonceStr, //随机串
        package: packageData,
        signType, //微信签名方式：
        paySign, //微信签名
      },
      (res) => {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          window.history.replace(
            '/jsy/qrpay/result?status=s&amount=' + cashPayAmt,
          );
        } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
          // handleCancelPay(uuid, cashPayAmt, orderNo, res.err_msg || '');
          history.replace('/jsy/qrpay/result?status=c&msg=您已取消支付');
        } else {
          // 上传日志
          // const wxTradeContext = {
          //   uuid: uuid,
          //   amt: cashPayAmt,
          //   orderNo: orderNo,
          //   err_msg: res.err_msg || '',
          // };
          // uploadLog('wechatJSTrade', wxTradeContext);
          history.replace(
            '/jsy/qrpay/result?status=f' +
              '&amount=' +
              cashPayAmt +
              '&msg=' +
              encodeURI('网络通讯异常，请尝试重新付款'),
          );
        }
      },
    );
  };
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    }
  } else {
    onBridgeReady();
  }
};

const pay = (api, { body }) => {
  fetch
    .post(api, body)
    .then((res) => {
      if (res.code === 0) {
        const {
          qrcode_url,
          cashPayAmt,
          sub_open_id,
          open_id,
          pay_info,
          orderNo,
        } = res.data || {};
        console.log(res.data);

        storage.setItem('openId', open_id);

        if (browser === 'ALIPAY') {
          location.replace(qrcode_url);
        }

        if (browser === 'WECHAT') {
          const { appId, timeStamp, nonceStr, signType, paySign, packageData } =
            JSON.parse(pay_info || '{}');
          // 支付参数
          callpay({
            appId,
            timeStamp,
            nonceStr,
            signType,
            paySign,
            packageData,
            cashPayAmt,
            orderNo,
            uuid: body.uid,
          });
        }

        // if (browser === 'UNIONPAY') {
        //   return location.replace(data.redirectUrl);
        // }
      } else {
        Toast.info(res.msg);
      }
    })
    .catch(() => Toast.info('网络错误，请稍后再试'));
};

export { storage, browser, pay, keyboardLayout };

// const aliPay = (params) => {
//   const { tradeNO, posSeqNo = '', realAmt = '', orderNo = '', uuid } = params;

//   // 由于js的载入是异步的，所以可以通过该方法，当AlipayJSBridgeReady事件发生后，再执行callback方法
//   function ready(callback) {
//     if (window.AlipayJSBridge) {
//       callback && callback();
//     } else {
//       document.addEventListener('AlipayJSBridgeReady', callback, false);
//     }
//   }

//   const tradePay = (tradeNO) => {
//     ready(() => {
//       // 通过传入交易号唤起快捷调用方式(注意tradeNO大小写严格)
//       AlipayJSBridge.call('tradePay', { tradeNO: tradeNO }, (data) => {
//         if ('9000' == data.resultCode) {
//           history.replace('/jsy/qrpay/result?status=s&posSeqNo=' + posSeqNo + '&amount=' + realAmt);
//         } else if (data.resultCode === '6001' || data.resultCode === '7001') {
//           handleCancelPay(uuid, realAmt, orderNo, null);
//           history.replace('/jsy/qrpay/result?status=c&msg=您已取消支付');
//         } else {
//           history.replace(
//             '/jsy/qrpay/result?status=f' +
//               '&amount=' +
//               realAmt +
//               '&msg=' +
//               encodeURI('网络通讯异常，请尝试重新付款'),
//           );
//         }
//       });
//     });
//   };

//   // 页面载入完成后即唤起收银台
//   tradePay(tradeNO);
// };

// const handleCancelPay = (uuid, amt, orderNo) => {
//   const cancleTradeParam = { uuid, amt, orderNo };

//   fetch.post('/trade/cancelTrade', cancleTradeParam, { noLoading: true });
// };

// const uploadLog = (moduleName, context) => {
//   var upLogUrl = '/trade/outPutLog';
//   var upLogUrlParam = { module: moduleName, context: context };
//   fetch.post(upLogUrl, upLogUrlParam).then(
//     (res) => {
//       console.log('upload log success', res);
//     },
//     function (err) {
//       console.log('upload log err', err);
//     },
//   );
// };
